package com.abocode.aichat.app.auth;


import com.abocode.aichat.app.constant.ErrorCode;
import com.abocode.aichat.app.exception.ContextRuntimeException;
import com.abocode.aichat.app.utils.StringUtil;
import com.abocode.aichat.app.vo.AuthorizationVo;
import com.abocode.aichat.app.vo.HttpHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by guanxf on 2015/12/16.
 */
//@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private HttpHelper httpHelper;
    @Value("${auth.checkid.resources}")
    private String resources;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (HandlerMethod.class.getSimpleName().equals(handler.getClass().getSimpleName())) {

            AuthorizationVo av = httpHelper.getAuthorizationVo(request);//鉴权
             String  token=av.getToken();
            if (StringUtil.isNullOrWhiteSpace(token)) {
                throw new ContextRuntimeException(ErrorCode.COMM_PARAMETER_INVALID, String.format("请求参数校验失败token is null",token));
            }

            if (httpHelper.isExpiredToken(token)) {
                throw new ContextRuntimeException(ErrorCode.COMM_TOKEN_IS_EXPIRED, String.format("Token失效，请重新登录",token));
            }

          String uid=httpHelper.getUid(token);
               String uri=request.getRequestURI();
                if(httpHelper.checkUri(uri,resources)){
                   String uidUid=uri.split("/")[2];
                    if(!uid.equals(uidUid)){
                        throw new ContextRuntimeException(ErrorCode.COMM_INVALID_REQUEST, String.format("非法请求"));
                    }
              }
        }
        request.setAttribute("time", System.currentTimeMillis());
        return super.preHandle(request, response, handler);
    }
}
